import { Request, Response } from 'express';
import { LessonPlan, ILessonPlan } from '../models/LessonPlan';
import { LessonPlanVersion } from '../models/LessonPlanVersion';
import { AuthRequest } from '../middleware/auth';
import { logger } from '../utils/logger';
import mongoose from 'mongoose';
import { ActivityService } from '../services/ActivityService';
import { NotificationService } from '../services/NotificationService';

export class LessonPlanController {
  // 获取教案列表
  public getAll = async (req: Request, res: Response): Promise<void> => {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      const skip = (page - 1) * limit;

      const query: any = { 
        isPublic: true,
        status: 'published' // 只显示已发布的教案
      };
      
      // 添加过滤条件
      if (req.query.subject) {
        query.subject = req.query.subject;
      }
      if (req.query.grade) {
        query.grade = req.query.grade;
      }
      if (req.query.courseType) {
        query.courseType = req.query.courseType;
      }
      
      // 对于公开教案列表，不允许查看草稿或归档状态
      // 如果前端传递了status参数，也只能是published
      if (req.query.status && req.query.status !== 'published') {
        query.status = 'published'; // 强制为published
      }

      // 构建排序
      const sortBy = req.query.sortBy as string || 'date';
      let sort: any = {};
      switch (sortBy) {
        case 'date':
          sort = { createdAt: -1 };
          break;
        case 'views':
          sort = { views: -1 };
          break;
        case 'likes':
          sort = { likes: -1 };
          break;
        case 'relevance':
        default:
          sort = { createdAt: -1 };
          break;
      }

      const [lessonPlans, total] = await Promise.all([
        LessonPlan.find(query)
          .populate('author', '_id name email avatar')
          .sort(sort)
          .skip(skip)
          .limit(limit),
        LessonPlan.countDocuments(query)
      ]);

      res.json({
        success: true,
        data: {
          lessonPlans,
          pagination: {
            current: page,
            limit,
            total,
            pages: Math.ceil(total / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取教案列表错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 获取单个教案
  public getById = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;

      // 先简单获取教案，不进行任何populate
      let lessonPlan = await LessonPlan.findById(id);

      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 增加浏览次数
      await LessonPlan.findByIdAndUpdate(id, { $inc: { views: 1 } });

      // 尝试populate相关数据
      try {
        lessonPlan = await LessonPlan.findById(id)
          .populate('author', '_id name email avatar');
        
        // 如果comments字段存在且不为空，尝试populate
        if (lessonPlan && lessonPlan.comments && lessonPlan.comments.length > 0) {
          try {
            lessonPlan = await LessonPlan.findById(id)
              .populate('author', '_id name email avatar')
              .populate({
                path: 'comments',
                populate: {
                  path: 'author',
                  select: '_id name avatar'
                }
              });
          } catch (commentError) {
            console.log('Failed to populate comments:', commentError);
          }
        }
      } catch (populateError) {
        console.log('Failed to populate author:', populateError);
      }

      // 检查教案是否存在
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 检查当前用户是否已点赞
      let isLiked = false;
      if ((req as AuthRequest).user) {
        const userId = (req as AuthRequest).user!.id;
        isLiked = lessonPlan.likedBy?.includes(userId) || false;
      }

      res.json({
        success: true,
        data: {
          ...lessonPlan.toObject(),
          isLiked
        }
      });
    } catch (error) {
      console.error('获取教案详情错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 创建教案
  public create = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const {
        title,
        content,
        subject,
        grade,
        courseType,
        tags,
        attachments,
        isPublic,
        status
      } = req.body;

      const lessonPlan = new LessonPlan({
        title,
        content,
        subject,
        grade,
        courseType,
        tags,
        attachments: attachments || [],
        author: req.user!.id,
        isPublic,
        status
      });

      await lessonPlan.save();

      // 填充作者信息
      await lessonPlan.populate('author', '_id name email');

      // 记录活动
      await ActivityService.log({
        userId: req.user!.id,
        type: 'create',
        target: 'lessonPlan',
        targetId: (lessonPlan._id as any).toString(),
        targetTitle: lessonPlan.title
      });

      // 如果是公开教案，通知所有其他用户
      if (lessonPlan.isPublic) {
        await NotificationService.notifyAllUsers({
          excludeUserId: req.user!.id,
          senderId: req.user!.id,
          type: 'lesson_published',
          title: '新的公开教案',
          content: `${req.user!.name} 发布了新的公开教案《${lessonPlan.title}》`,
          relatedModel: 'LessonPlan',
          relatedId: (lessonPlan._id as any).toString()
        });
      }

      res.status(201).json({
        success: true,
        message: '教案创建成功',
        data: lessonPlan
      });
    } catch (error) {
      console.error('创建教案错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 更新教案
  public update = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const updateData = req.body;

      const lessonPlan = await LessonPlan.findById(id);
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 检查权限：只有作者可以修改
      if (lessonPlan.author.toString() !== req.user!.id) {
        res.status(403).json({
          success: false,
          message: '没有权限修改此教案'
        });
        return;
      }

      // 如果内容有重大更改，创建版本历史并更新版本号
      if (updateData.content && updateData.content !== lessonPlan.content) {
        // 保存当前版本到历史记录
        const versionHistory = new LessonPlanVersion({
          lessonPlanId: lessonPlan._id,
          version: lessonPlan.version,
          title: lessonPlan.title,
          content: lessonPlan.content,
          subject: lessonPlan.subject,
          grade: lessonPlan.grade,
          courseType: lessonPlan.courseType,
          tags: lessonPlan.tags,
          changeLog: updateData.changeLog || '内容更新',
          createdBy: req.user!.id
        });
        await versionHistory.save();
        
        updateData.version = lessonPlan.version + 1;
      }

      const updatedLessonPlan = await LessonPlan.findByIdAndUpdate(
        id,
        updateData,
        { new: true, runValidators: true }
      ).populate('author', '_id name email');

      // 记录更新活动
      await ActivityService.log({
        userId: req.user!.id,
        type: 'update',
        target: 'lessonPlan',
        targetId: (updatedLessonPlan as any)._id.toString(),
        targetTitle: updatedLessonPlan!.title
      });

      res.json({
        success: true,
        message: '教案更新成功',
        data: updatedLessonPlan
      });
    } catch (error) {
      console.error('更新教案错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 删除教案
  public delete = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const { id } = req.params;

      const lessonPlan = await LessonPlan.findById(id);
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 检查权限：只有作者可以删除
      if (lessonPlan.author.toString() !== req.user!.id) {
        res.status(403).json({
          success: false,
          message: '没有权限删除此教案'
        });
        return;
      }

      // 在删除前记录活动
      await ActivityService.log({
        userId: req.user!.id,
        type: 'delete',
        target: 'lessonPlan',
        targetId: (lessonPlan._id as any).toString(),
        targetTitle: lessonPlan.title
      });

      await LessonPlan.findByIdAndDelete(id);

      res.json({
        success: true,
        message: '教案删除成功'
      });
    } catch (error) {
      console.error('删除教案错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 保存草稿
  public saveDraft = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const {
        title,
        content,
        subject,
        grade,
        courseType,
        tags,
        attachments,
        isPublic = true
      } = req.body;

      const lessonPlan = new LessonPlan({
        title: title || '未命名教案',
        content: content || '',
        subject: subject || '',
        grade: grade || '',
        courseType: courseType || '',
        tags: tags || [],
        attachments: attachments || [],
        author: req.user!.id,
        isPublic,
        status: 'draft'
      });

      await lessonPlan.save();
      await lessonPlan.populate('author', '_id name email');

      res.status(201).json({
        success: true,
        message: '草稿保存成功',
        data: lessonPlan
      });
    } catch (error) {
      console.error('保存草稿错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 更新草稿
  public updateDraft = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const updateData = req.body;

      const lessonPlan = await LessonPlan.findById(id);
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 检查权限
      if (lessonPlan.author.toString() !== req.user!.id) {
        res.status(403).json({
          success: false,
          message: '没有权限修改此教案'
        });
        return;
      }

      // 草稿状态下更新不增加版本号
      const updatedLessonPlan = await LessonPlan.findByIdAndUpdate(
        id,
        { ...updateData, status: 'draft' },
        { new: true, runValidators: true }
      ).populate('author', '_id name email');

      res.json({
        success: true,
        message: '草稿更新成功',
        data: updatedLessonPlan
      });
    } catch (error) {
      console.error('更新草稿错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 发布教案
  public publish = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const { id } = req.params;

      const lessonPlan = await LessonPlan.findById(id);
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 检查权限
      if (lessonPlan.author.toString() !== req.user!.id) {
        res.status(403).json({
          success: false,
          message: '没有权限发布此教案'
        });
        return;
      }

      // 验证必需字段
      if (!lessonPlan.title || !lessonPlan.content || !lessonPlan.subject || !lessonPlan.grade || !lessonPlan.courseType) {
        res.status(400).json({
          success: false,
          message: '教案信息不完整，无法发布'
        });
        return;
      }

      const updatedLessonPlan = await LessonPlan.findByIdAndUpdate(
        id,
        { 
          status: 'published',
          version: lessonPlan.version + 1
        },
        { new: true, runValidators: true }
      ).populate('author', '_id name email');

      // 记录发布活动
      await ActivityService.log({
        userId: req.user!.id,
        type: 'publish',
        target: 'lessonPlan',
        targetId: (updatedLessonPlan as any)._id.toString(),
        targetTitle: updatedLessonPlan!.title
      });

      // 如果是公开教案，给所有用户发送通知
      if (updatedLessonPlan!.isPublic) {
        await NotificationService.notifyAllUsers({
          excludeUserId: req.user!.id,
          senderId: req.user!.id,
          type: 'lesson_published',
          title: '新教案发布',
          content: `${req.user!.name || '用户'} 发布了新教案《${updatedLessonPlan!.title}》`,
          relatedModel: 'LessonPlan',
          relatedId: (updatedLessonPlan as any)._id.toString()
        });
      }

      res.json({
        success: true,
        message: '教案发布成功',
        data: updatedLessonPlan
      });
    } catch (error) {
      console.error('发布教案错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 归档教案
  public archive = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const { id } = req.params;

      const lessonPlan = await LessonPlan.findById(id);
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 检查权限
      if (lessonPlan.author.toString() !== req.user!.id) {
        res.status(403).json({
          success: false,
          message: '没有权限归档此教案'
        });
        return;
      }

      const updatedLessonPlan = await LessonPlan.findByIdAndUpdate(
        id,
        { status: 'archived' },
        { new: true, runValidators: true }
      ).populate('author', '_id name email');

      // 记录归档活动
      await ActivityService.log({
        userId: req.user!.id,
        type: 'archive',
        target: 'lessonPlan',
        targetId: (updatedLessonPlan as any)._id.toString(),
        targetTitle: updatedLessonPlan!.title
      });

      res.json({
        success: true,
        message: '教案归档成功',
        data: updatedLessonPlan
      });
    } catch (error) {
      console.error('归档教案错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 获取用户的教案列表
  public getMyLessonPlans = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      const skip = (page - 1) * limit;

      const query: any = { author: req.user!.id };
      
      // 添加过滤条件
      if (req.query.status) {
        query.status = req.query.status;
      }
      if (req.query.subject) {
        query.subject = req.query.subject;
      }

      const [lessonPlans, total] = await Promise.all([
        LessonPlan.find(query)
          .populate('author', '_id name email')
          .sort({ updatedAt: -1 })
          .skip(skip)
          .limit(limit),
        LessonPlan.countDocuments(query)
      ]);

      res.json({
        success: true,
        data: {
          lessonPlans,
          pagination: {
            current: page,
            limit,
            total,
            pages: Math.ceil(total / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取我的教案列表错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 获取教案版本历史
  public getVersionHistory = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      const skip = (page - 1) * limit;

      const lessonPlan = await LessonPlan.findById(id);
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      const [versions, total] = await Promise.all([
        LessonPlanVersion.find({ lessonPlanId: id })
          .populate('createdBy', 'name email')
          .sort({ version: -1 })
          .skip(skip)
          .limit(limit),
        LessonPlanVersion.countDocuments({ lessonPlanId: id })
      ]);

      res.json({
        success: true,
        data: {
          versions,
          pagination: {
            current: page,
            limit,
            total,
            pages: Math.ceil(total / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取版本历史错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 获取特定版本的教案
  public getSpecificVersion = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id, version } = req.params;

      const versionData = await LessonPlanVersion.findOne({
        lessonPlanId: id,
        version: parseInt(version)
      }).populate('createdBy', 'name email');

      if (!versionData) {
        res.status(404).json({
          success: false,
          message: '版本不存在'
        });
        return;
      }

      res.json({
        success: true,
        data: versionData
      });
    } catch (error) {
      console.error('获取特定版本错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 恢复到指定版本
  public restoreVersion = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const { id, version } = req.params;

      const lessonPlan = await LessonPlan.findById(id);
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 检查权限
      if (lessonPlan.author.toString() !== req.user!.id) {
        res.status(403).json({
          success: false,
          message: '没有权限恢复此教案版本'
        });
        return;
      }

      const versionData = await LessonPlanVersion.findOne({
        lessonPlanId: id,
        version: parseInt(version)
      });

      if (!versionData) {
        res.status(404).json({
          success: false,
          message: '版本不存在'
        });
        return;
      }

      // 保存当前版本到历史记录
      const currentVersionHistory = new LessonPlanVersion({
        lessonPlanId: lessonPlan._id,
        version: lessonPlan.version,
        title: lessonPlan.title,
        content: lessonPlan.content,
        subject: lessonPlan.subject,
        grade: lessonPlan.grade,
        courseType: lessonPlan.courseType,
        tags: lessonPlan.tags,
        changeLog: `恢复到版本 ${version}`,
        createdBy: req.user!.id
      });
      await currentVersionHistory.save();

      // 更新教案到指定版本
      const updatedLessonPlan = await LessonPlan.findByIdAndUpdate(
        id,
        {
          title: versionData.title,
          content: versionData.content,
          subject: versionData.subject,
          grade: versionData.grade,
          courseType: versionData.courseType,
          tags: versionData.tags,
          version: lessonPlan.version + 1
        },
        { new: true, runValidators: true }
      ).populate('author', '_id name email');

      res.json({
        success: true,
        message: `成功恢复到版本 ${version}`,
        data: updatedLessonPlan
      });
    } catch (error) {
      console.error('恢复版本错误:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  };

  // 搜索教案
  public search = async (req: Request, res: Response): Promise<void> => {
    try {
      const { 
        q, // 搜索关键词
        subject,
        grade,
        courseType,
        tags,
        author,
        status,
        sortBy = 'relevance', // relevance, date, views, likes
        page = 1,
        limit = 10
      } = req.query;

      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const query: any = {};

      // 权限控制：未登录用户只能看公开且已发布的教案
      if (!(req as AuthRequest).user) {
        query.isPublic = true;
        query.status = 'published';
      } else {
        // 已登录用户的搜索逻辑
        const currentUser = (req as AuthRequest).user;
        
        if (author && author === currentUser?.id) {
          // 搜索自己的教案，可以看到所有状态的
          query.author = author;
          // 搜索自己的教案时，允许指定状态过滤
          if (status) {
            query.status = status;
          }
        } else {
          // 搜索他人或全部教案，只能看公开的
          query.isPublic = true;
          // 对于公开搜索，强制只能看已发布的教案
          query.status = 'published';
        }
      }

      // 文本搜索 - 使用正则表达式模糊匹配
      if (q && typeof q === 'string' && q.trim()) {
        const searchTerm = q.trim();
        
        // 使用正则表达式进行模糊匹配
        query.$or = [
          { title: { $regex: searchTerm, $options: 'i' } },
          { content: { $regex: searchTerm, $options: 'i' } },
          { tags: { $in: [new RegExp(searchTerm, 'i')] } }
        ];
      }

      // 添加过滤条件
      if (subject) {
        // 支持多个subject
        if (Array.isArray(subject)) {
          query.subject = { $in: subject };
        } else {
          query.subject = subject;
        }
      }

      if (grade) {
        if (Array.isArray(grade)) {
          query.grade = { $in: grade };
        } else {
          query.grade = grade;
        }
      }

      if (courseType) {
        if (Array.isArray(courseType)) {
          query.courseType = { $in: courseType };
        } else {
          query.courseType = courseType;
        }
      }

      if (tags) {
        // 标签搜索，支持多个标签
        const tagArray = Array.isArray(tags) ? tags : [tags];
        query.tags = { $in: tagArray };
      }

      // 检查是否有任何搜索条件
      const qStr = typeof q === 'string' ? q : '';
      const hasSearchConditions = (qStr && qStr.trim()) || subject || grade || courseType || tags;
      
      // 如果没有任何搜索条件，返回空结果
      if (!hasSearchConditions) {
        logger.info('搜索请求没有任何条件，返回空结果');
        res.json({
          success: true,
          data: {
            lessonPlans: [],
            pagination: {
              page: pageNum,
              limit: limitNum,
              total: 0,
              totalPages: 0
            },
            searchInfo: {
              query: '',
              filters: {
                subject,
                grade,
                courseType,
                tags,
                author,
                status
              },
              sortBy
            }
          }
        });
        return;
      }

      // 构建排序
      let sort: any = {};
      let useTextScore = false;
      
      switch (sortBy) {
        case 'date':
          sort = { createdAt: -1 };
          break;
        case 'views':
          sort = { views: -1 };
          break;
        case 'likes':
          sort = { likes: -1 };
          break;
        case 'relevance':
        default:
          // 按创建时间排序（移除文本相关性排序）
          sort = { createdAt: -1 };
          break;
      }

      console.log('Executing search query:', JSON.stringify(query, null, 2));
      console.log('Search sort:', JSON.stringify(sort, null, 2));

      // 执行查询
      const lessonPlans = await LessonPlan.find(query)
        .populate('author', '_id name email avatar')
        .sort(sort)
        .skip(skip)
        .limit(limitNum);

      const total = await LessonPlan.countDocuments(query);

      console.log('Found lessonPlans:', lessonPlans.length, 'Total:', total);

      // 处理搜索结果，添加高亮信息
      const results = lessonPlans.map((plan: any) => {
        const plainPlan = plan.toObject();
        
        // 如果有搜索关键词，添加高亮信息
        if (q && typeof q === 'string') {
          const searchTerm = q.trim().toLowerCase();
          
          // 简单的高亮实现，标记匹配的位置
          const highlights: any = {};
          
          // 标题高亮
          const titleLower = plan.title.toLowerCase();
          if (titleLower.includes(searchTerm)) {
            const index = titleLower.indexOf(searchTerm);
            highlights.title = {
              text: plan.title,
              matches: [{
                start: index,
                end: index + searchTerm.length
              }]
            };
          }
          
          // 内容高亮（只返回包含关键词的片段）
          const contentLower = plan.content.toLowerCase();
          if (contentLower.includes(searchTerm)) {
            const index = contentLower.indexOf(searchTerm);
            const start = Math.max(0, index - 50);
            const end = Math.min(plan.content.length, index + searchTerm.length + 50);
            
            highlights.content = {
              text: plan.content.substring(start, end),
              matches: [{
                start: index - start,
                end: index - start + searchTerm.length
              }]
            };
          }
          
          // 标签高亮
          const matchedTags = plan.tags.filter((tag: string) => 
            tag.toLowerCase().includes(searchTerm)
          );
          if (matchedTags.length > 0) {
            highlights.tags = matchedTags;
          }
          
          plainPlan.highlights = highlights;
        }
        
        return plainPlan;
      });

      logger.info('教案搜索完成', {
        query: q,
        total,
        page: pageNum,
        resultsCount: results.length
      });

      res.json({
        success: true,
        data: {
          lessonPlans: results,
          pagination: {
            page: pageNum,
            limit: limitNum,
            total,
            totalPages: Math.ceil(total / limitNum)
          },
          searchInfo: {
            query: q || '',
            filters: {
              subject,
              grade,
              courseType,
              tags,
              author,
              status
            },
            sortBy
          }
        }
      });
    } catch (error: any) {
      logger.error('搜索教案错误:', { 
        error: error.message,
        query: req.query,
        stack: error.stack
      });
      res.status(500).json({
        success: false,
        message: '搜索失败，请稍后重试',
        code: 'SEARCH_ERROR'
      });
    }
  };

  // 获取热门搜索
  public getHotSearches = async (req: Request, res: Response): Promise<void> => {
    try {
      const { limit = 10 } = req.query;
      const limitNum = parseInt(limit as string);

      // 这里简单返回一些预设的热门搜索
      // 实际项目中应该统计搜索频率
      const hotSearches = [
        { keyword: '数学', count: 156 },
        { keyword: '语文', count: 143 },
        { keyword: '英语', count: 132 },
        { keyword: '物理', count: 98 },
        { keyword: '化学', count: 87 },
        { keyword: '生物', count: 76 },
        { keyword: '历史', count: 65 },
        { keyword: '地理', count: 54 },
        { keyword: '政治', count: 43 },
        { keyword: '美术', count: 32 }
      ].slice(0, limitNum);

      res.json({
        success: true,
        data: hotSearches
      });
    } catch (error: any) {
      logger.error('获取热门搜索错误:', { error: error.message });
      res.status(500).json({
        success: false,
        message: '获取热门搜索失败',
        code: 'HOT_SEARCH_ERROR'
      });
    }
  };

  // 切换点赞状态
  public toggleLike = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const { id } = req.params;

      if (!req.user) {
        res.status(401).json({
          success: false,
          message: '请先登录'
        });
        return;
      }

      const lessonPlan = await LessonPlan.findById(id);
      if (!lessonPlan) {
        res.status(404).json({
          success: false,
          message: '教案不存在'
        });
        return;
      }

      // 检查用户是否已经点赞
      const userId = req.user.id;
      const likedIndex = lessonPlan.likedBy?.indexOf(userId) ?? -1;
      let isLiked = false;

      if (likedIndex > -1) {
        // 取消点赞
        lessonPlan.likedBy?.splice(likedIndex, 1);
        lessonPlan.likes = Math.max(0, (lessonPlan.likes || 0) - 1);
      } else {
        // 添加点赞
        if (!lessonPlan.likedBy) {
          lessonPlan.likedBy = [];
        }
        lessonPlan.likedBy.push(userId);
        lessonPlan.likes = (lessonPlan.likes || 0) + 1;
        isLiked = true;
      }

      await lessonPlan.save();

      // 记录点赞活动
      if (isLiked) {
        await ActivityService.log({
          userId: req.user.id,
          type: 'like',
          target: 'lessonPlan',
          targetId: (lessonPlan._id as any).toString(),
          targetTitle: lessonPlan.title
        });
      }

      res.json({
        success: true,
        message: isLiked ? '点赞成功' : '取消点赞成功',
        data: {
          liked: isLiked,
          likes: lessonPlan.likes
        }
      });
    } catch (error) {
      console.error('切换点赞状态错误:', error);
      res.status(500).json({
        success: false,
        message: '操作失败'
      });
    }
  };

  // 获取分类统计
  public getCategoryStats = async (req: Request, res: Response): Promise<void> => {
    try {
      logger.info('获取分类统计请求');

      // 基础查询条件
      const baseQuery = {
        isPublic: true,
        status: 'published'
      };

      // 并行执行所有聚合查询
      const [
        subjectStats,
        gradeStats,
        courseTypeStats,
        tagStats,
        totalCount
      ] = await Promise.all([
        // 按学科统计
        LessonPlan.aggregate([
          { $match: baseQuery },
          {
            $group: {
              _id: '$subject',
              count: { $sum: 1 },
              avgViews: { $avg: '$views' },
              avgLikes: { $avg: '$likes' }
            }
          },
          {
            $lookup: {
              from: 'categories',
              localField: '_id',
              foreignField: '_id',
              as: 'categoryInfo'
            }
          },
          {
            $unwind: {
              path: '$categoryInfo',
              preserveNullAndEmptyArrays: true
            }
          },
          {
            $project: {
              _id: 1,
              name: { $ifNull: ['$categoryInfo.name', '$_id'] },
              count: 1,
              avgViews: { $round: ['$avgViews', 0] },
              avgLikes: { $round: ['$avgLikes', 0] }
            }
          },
          { $sort: { count: -1 } }
        ]),

        // 按年级统计
        LessonPlan.aggregate([
          { $match: baseQuery },
          {
            $group: {
              _id: '$grade',
              count: { $sum: 1 }
            }
          },
          {
            $lookup: {
              from: 'categories',
              localField: '_id',
              foreignField: '_id',
              as: 'categoryInfo'
            }
          },
          {
            $unwind: {
              path: '$categoryInfo',
              preserveNullAndEmptyArrays: true
            }
          },
          {
            $project: {
              _id: 1,
              name: { $ifNull: ['$categoryInfo.name', '$_id'] },
              count: 1
            }
          },
          { $sort: { count: -1 } }
        ]),

        // 按课程类型统计
        LessonPlan.aggregate([
          { $match: baseQuery },
          {
            $group: {
              _id: '$courseType',
              count: { $sum: 1 }
            }
          },
          {
            $lookup: {
              from: 'categories',
              localField: '_id',
              foreignField: '_id',
              as: 'categoryInfo'
            }
          },
          {
            $unwind: {
              path: '$categoryInfo',
              preserveNullAndEmptyArrays: true
            }
          },
          {
            $project: {
              _id: 1,
              name: { $ifNull: ['$categoryInfo.name', '$_id'] },
              count: 1
            }
          },
          { $sort: { count: -1 } }
        ]),

        // 标签统计（前20个热门标签）
        LessonPlan.aggregate([
          { $match: baseQuery },
          { $unwind: '$tags' },
          {
            $group: {
              _id: '$tags',
              count: { $sum: 1 }
            }
          },
          { $sort: { count: -1 } },
          { $limit: 20 },
          {
            $project: {
              tag: '$_id',
              count: 1,
              _id: 0
            }
          }
        ]),

        // 总数统计
        LessonPlan.countDocuments(baseQuery)
      ]);

      // 计算百分比
      const addPercentage = (stats: any[]) => {
        return stats.map(stat => ({
          ...stat,
          percentage: totalCount > 0 ? Math.round((stat.count / totalCount) * 100) : 0
        }));
      };

      logger.info('分类统计完成', {
        subjectCount: subjectStats.length,
        gradeCount: gradeStats.length,
        courseTypeCount: courseTypeStats.length,
        tagCount: tagStats.length,
        totalCount
      });

      res.json({
        success: true,
        data: {
          subjects: addPercentage(subjectStats),
          grades: addPercentage(gradeStats),
          courseTypes: addPercentage(courseTypeStats),
          tags: tagStats,
          summary: {
            totalLessonPlans: totalCount,
            totalSubjects: subjectStats.length,
            totalGrades: gradeStats.length,
            totalCourseTypes: courseTypeStats.length,
            totalTags: tagStats.length
          }
        }
      });
    } catch (error: any) {
      logger.error('获取分类统计错误:', { 
        error: error.message,
        stack: error.stack
      });
      res.status(500).json({
        success: false,
        message: '获取分类统计失败，请稍后重试',
        code: 'STATS_ERROR'
      });
    }
  };
}